<?php
/*
 * @Author: ZhaohangYang <yangzhaohang@comsenz-service.com>
 * @Date: 2021-06-23 16:58:47
 * @Description: 伙伴智慧大客户研发部
 */
namespace App\ModesXinghua;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Log;

class XinghuaBasic
{
    public $apiUrl;
    public $apiClient;
    public function __construct()
    {
        $this->apiUrl = env('XINGHUA_TEST') ? env('XINGHUA_URL_TEST') : env('XINGHUA_URL');
    }

    public function sendRequest($url, $body)
    {
        try {
            $params       = array('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180);
            $client       = new \SoapClient(storage_path() . '/webservices/wsdl', $params);
            $response_obj = $client->__soapCall('OutBoundData', ['OutBoundData' => ['Input' => $body]]);

            $response = simplexml_load_string($response_obj->payload, "SimpleXMLElement", LIBXML_NOCDATA);
            return json_decode(json_encode($response), true);

        } catch (\SoapFault $e) {
            Log::error($e->getMessage());
            throw new \Exception($e->getMessage(), 1);

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            throw new \Exception($e->getMessage(), 1);
        }
    }

    public function getApiClient()
    {
        if (!$this->apiClient) {
            // 生成不进行效验,错误不打断返回详细信息的客户端
            $this->apiClient = new Client(['base_uri' => $this->apiUrl, 'timeout' => 600, 'verify' => false, 'http_errors' => true]);
        }
        return $this->apiClient;
    }

    public function getRequest($method, $url, $body = [], $options = [])
    {
        $headers = $this->defaultHeader($options);
        return new Request($method, $url, $headers, $body);
    }

    public function defaultHeader($options = [])
    {

        $default_headers = [
            'Content-Type' => 'application/xml',
        ];
        $headers = isset($options['headers']) ? $options['headers'] : [];

        return $headers + $default_headers;
    }

    public function requestJsonSync($request)
    {
        try {
            $response = $this->getApiClient()->send($request);
        } catch (ServerException $e) {
            $response = $e->getResponse();
        }

        $response_obj = simplexml_load_string($response->getBody(), "SimpleXMLElement", LIBXML_NOCDATA);
        return json_decode(json_encode($response_obj), true);
    }

    /**
     * 效验请求返回结果
     *
     * @param [type] $response
     * @param string $location
     * @return void
     */
    public function verifyResponse($response, $location = '', $type = 'throw')
    {
    }

    public function collectError($message)
    {
    }
}
